package com.example.demo.common.utils;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AesUtil {
   // aes 加密
    public static String encryptData(String data, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
        int plaintextLength = dataBytes.length;
        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
        SecretKeySpec keyspace = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec inspect = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, keyspace, inspect);
        byte[] encrypted = cipher.doFinal(plaintext);
        return new String(Base64.encodeBase64(encrypted));

    }

   // aes 解密
    public static String decryptData(String data, String key, String IV) throws Exception {
        byte[] encrypted1 = Base64.decodeBase64(data.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original, StandardCharsets.UTF_8);
        return originalString;
    }
}
